package com.baofu.paycore.biz.paycore.handler.impl;

import com.baofu.account.service.facade.model.request.ReverseReqDTO;
import com.baofu.paycore.biz.engine.result.CommandResult;
import com.baofu.paycore.biz.external.account.AccountService;
import com.baofu.paycore.biz.external.account.converter.AccountRequestConverter;
import com.baofu.paycore.biz.model.BackPayBO;
import com.baofu.paycore.biz.paycore.converter.BO2BOConverter;
import com.baofu.paycore.biz.paycore.handler.BaseHandler;
import com.baofu.paycore.common.exception.PayCoreBizException;
import com.baofu.paycore.dal.model.SubTransferDO;
import com.baofu.paycore.manager.model.AccountRespBO;
import com.baofu.paycore.manager.model.RechargeBO;
import com.baofu.paycore.manager.model.ResponseBO;
import com.baofu.paycore.manager.model.TransferBO;
import com.baofu.paycore.manager.storage.impl.TransferManager;
import com.baofu.paycore.manager.storer.TransferOrderRepository;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.service.facade.enums.ServiceCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 转账撤销订单
 *
 * <p/>
 *      1、订单处理
 * </p>
 * User: LZQ Date: 2016/04/20  Version: 1.0
 */
@Service
@Slf4j
public class CancelTransferHandler extends BaseHandler<TransferBO,RechargeBO> {

    /**
     * 持久服务
     */
    @Autowired
    private TransferOrderRepository cancelTransferOrderRepository;

    /**
     * 账务转账服务
     */
    @Autowired
    private AccountService accountService;

    /**
     * 转账管理manager
     */
    private TransferManager transferManager;



    @Override
    public BackPayBO process(TransferBO transferBO) {
        log.debug("转账撤销开始处理：{}", transferBO);
        doExecute(transferBO);
        log.debug("转账撤销结果：{}", transferBO);
        return BO2BOConverter.transferBO2BackPayBO(transferBO);
    }

    /**
     * 激活领域对象
     *
     * @param orderId 订单ID
     * @return 订单对象
     */
    @Override
    public TransferBO activeOrder(String orderId) {
        TransferBO cancelTransferBO = cancelTransferOrderRepository.load(orderId);
        if (cancelTransferBO == null) {
            log.error("找不到订单:{}", orderId);
            throw new PayCoreBizException(PayCoreErrorCode.ORDER_IS_NOT_EXISTED);
        }
        return cancelTransferBO;
    }

    @Override
    /**
     * 查询订单信息
     *
     * @param payNo   支付单号
     * @return 订单对象
     */
    public TransferBO queryOrderByPayNo(String payNo) {
        return activeOrder(payNo);
    }

    /**
     * 前置检查
     *
     * @param order 订单
     */
    @Override
    protected void checkBeforeProcess(TransferBO order) {
        order.checkStatus();
    }

    /**
     * 生成指令
     *
     * @param order 单据
     */
    @Override
    protected void processOrders(TransferBO order) {
        //1、账务撤销
        ReverseReqDTO reverseReqDTO = AccountRequestConverter.convert2TReverseDTO(order);
        AccountRespBO accountRespBO = accountService.cancel(order.getPayNo(), ServiceCodeEnum.CANCEL.getCode(),reverseReqDTO);
        setStatus(order,accountRespBO);
    }

    /**
     * 设置状态
     */
    private void setStatus(TransferBO order,AccountRespBO accountRespBO){
        SubTransferDO subTransferDO = order.getSubTransferDO().get(0);
        order.setRealFlag(accountRespBO.isRealRtn());
        order.setErrorCode(accountRespBO.getErrorCode());
        order.setErrorMsg(accountRespBO.getErrorMsg());
        order.setStatus(accountRespBO.getStatus());

        subTransferDO.setStatus(accountRespBO.getStatus());
        subTransferDO.setTransDate(accountRespBO.getAccDate());
        subTransferDO.setTransReceiptNo(accountRespBO.getReceiptNo());
        subTransferDO.setErrorReason(accountRespBO.getErrorMsg());
        subTransferDO.setErrorCode(accountRespBO.getErrorCode());
    }

    /**
     * 持久化对象
     *
     * @param order 单据
     */
    @Override
    protected void reStore(TransferBO order) {

        cancelTransferOrderRepository.updateCancelOrder(order);
    }

    /**
     * 指令完成后处理
     *
     * @param order     领域模型
     * @param cmdResult 指令处理结果
     */
    @Override
    protected void processAfter(TransferBO order, Map<String, CommandResult> cmdResult) {

    }

    /**
     * 需重试接口 对内部资金单的重试（订单状态推进）
     *
     * @param transferBO 支付订单对象
     * @return ResponseBO
     * @throws RuntimeException 出现异常时表示重试没有成功（子类方法实现中不可捕获异常）
     */
    public ResponseBO dalInnerFundProc(TransferBO transferBO) throws RuntimeException {
        transferBO.setOldTransferBO(activeOrder(transferBO.getOldPayNo()));

        BackPayBO backPayBO = process(transferBO);
        ResponseBO responseBO = new ResponseBO();
        responseBO.setStatus(backPayBO.getStatus());
        responseBO.setErrorCode(backPayBO.getErrorCode());
        responseBO.setErrorMsg(backPayBO.getErrorMsg());
        responseBO.setOppTrDate(backPayBO.getResponseDate());
        responseBO.setRequestNo(backPayBO.getRequestBizNo());
        responseBO.setTotalAmt(backPayBO.getAmt());
        responseBO.setRealFlag(backPayBO.isRealFlag());
        return responseBO;
    }
}